import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from '@/App.vue';
import router from '@/router';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import '@/assets/icon/iconfont.css';
import '@/assets/base.scss';
import HljsVuePlugin from '@highlightjs/vue-plugin';
import "highlight.js/styles/atom-one-light.css";
import 'highlight.js/lib/common';
import Message from '@/utils/Message';
import Confirm from '@/utils/Confirm';
import Verify from '@/utils/Verify';
import Utils from '@/utils/Utils';
import Icon from "@/components/Icon.vue";
import Table from '@/components/Table.vue';
import Dialog from '@/components/Dialog.vue';
import NoData from '@/components/NoData.vue';
import Window from '@/components/Window.vue';
import Navigation from '@/components/Navigation.vue';
import FolderSelect from '@/components/FolderSelect.vue';
import Avatar from '@/components/Avatar.vue';
import http from "@/utils/http";
import { ElMessage, ElMessageBox } from 'element-plus';
const app = createApp(App);
// 定义全局注入 ID 的函数
const getUserID = async (app) => {
    try {
        const res = await http.get("/user/getId");
        console.log(res.data);
        app.provide("userID", res.data); // 提供 userId
    } catch (error) {
        console.error("获取用户 ID 失败: ", error);
        app.provide("userID", null); // 处理错误并提供 null
    }
};

// 在路由守卫中检查 access-token 并调用 getUserID
router.beforeEach(async (to, from, next) => {
    const accessToken = localStorage.getItem('access-token');
    if (accessToken) {
        await getUserID(app);
    }
    next();
});

// 提供全局消息和确认对话框
app.provide('$message', ElMessage);
app.provide('$confirm', ElMessageBox.confirm);

app.use(ElementPlus);
app.use(createPinia());
app.use(HljsVuePlugin);
app.use(router);

app.component("Icon", Icon);
app.component("Table", Table);
app.component("Dialog", Dialog);
app.component("NoData", NoData);
app.component("Window", Window);
app.component("Navigation", Navigation);
app.component("FolderSelect", FolderSelect);
app.component("Avatar", Avatar);

// 配置全局变量
app.config.globalProperties.Request = Request;
app.config.globalProperties.Message = Message;
app.config.globalProperties.Confirm = Confirm;
app.config.globalProperties.Verify = Verify;
app.config.globalProperties.Utils = Utils;
app.config.globalProperties.globalInfo = {
    avatarUrl: "/api/getAvatar/",
    imageUrl: "/api/file/getImage/"
};

app.mount('#app');